<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="mx-auto max-w-7xl">
      <!-- 顶部操作区 -->
      <div
        class="mb-6 flex items-center justify-between bg-white p-4 rounded-lg shadow-sm"
      >
        <div></div>
        <div class="flex items-center gap-4">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            class="w-48"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
          <el-select
            v-model="searchForm.userRole"
            placeholder="请选择角色"
            class="w-48"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
          <el-button
            type="primary"
            class="!rounded-button"
            @click="handleSearch"
          >
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button class="!rounded-button" @click="resetSearch">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
      <!-- 表格区域 -->
      <div
        class="bg-white p-4 rounded-lg shadow-sm flex flex-col min-h-[200px]"
      >
        <el-table
          v-model:selection="selectedRows"
          :data="tableData"
          border
          stripe
          style="width: 100%; flex: 1"
          @sort-change="handleSortChange"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column
            prop="userAccount"
            label="用户账号"
            sortable="custom"
          />
          <el-table-column prop="userName" label="用户名称" sortable="custom" />
          <el-table-column prop="userAvatar" label="用户头像">
            <template #default="{ row }">
              <img :src="row.userAvatar" alt="用户头像" width="50" />
            </template>
          </el-table-column>
          <el-table-column
            prop="userProfile"
            label="用户简介"
            show-overflow-tooltip
          />
          <el-table-column prop="userRole" label="用户角色">
            <template #default="{ row }">
              <el-tag :type="row.userRole === 'admin' ? 'danger' : 'success'">
                {{ row.userRole === "admin" ? "管理员" : "普通用户" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            sortable="custom"
          />
          <el-table-column
            prop="updateTime"
            label="更新时间"
            sortable="custom"
          />
          <el-table-column prop="isDelete" label="是否删除">
            <template #default="{ row }">
              <el-tag :type="row.isDelete === 1 ? 'danger' : 'success'">
                {{ row.isDelete === 1 ? "已删除" : "正常" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                class="!rounded-button"
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="danger"
                class="!rounded-button ml-2"
                @click="handleDisable(row)"
              >
                <el-icon><CircleClose /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div></div>
        <!-- 分页 -->
        <div style="display: flex" class="block">
          <el-pagination
            class="block"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            :total="tableData.length"
            layout="pager"
          />
        </div>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="用户密码" prop="userPassword">
          <el-input
            v-model="formData.userPassword"
            type="password"
            placeholder="请输入用户密码"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户头像" prop="userAvatar">
          <el-input
            v-model="formData.userAvatar"
            placeholder="请输入用户头像链接"
          />
        </el-form-item>
        <el-form-item label="用户简介" prop="userProfile">
          <el-input
            v-model="formData.userProfile"
            type="textarea"
            :rows="3"
            placeholder="请输入用户简介"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="userRole">
          <el-select
            v-model="formData.userRole"
            placeholder="请选择用户角色"
            class="w-full"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除" prop="isDelete">
          <el-select
            v-model="formData.isDelete"
            placeholder="请选择是否删除"
            class="w-full"
          >
            <el-option label="正常" value="0" />
            <el-option label="已删除" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="!rounded-button" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button
            class="!rounded-button"
            type="primary"
            @click="handleSubmit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  CircleClose,
  Edit,
  Plus,
  Search,
  Refresh,
  User,
} from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import {
  UserControllerService,
  UserUpdateRequest,
} from "../../../xiongoj_backendapi";
import { UserAddRequest } from "../../../xiongoj_backendapi";
import { UserQueryRequest } from "../../../xiongoj_backendapi";
import { DeleteRequest } from "../../../xiongoj_backendapi";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

// 搜索表单
const searchForm = reactive({
  userAccount: "",
  userName: "",
  userRole: "",
});

// 角色选项
const roleOptions = [
  { label: "管理员", value: "admin" },
  { label: "普通用户", value: "user" },
];

// 表格数据
const tableData = ref<any[]>([]);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 选中的行
const selectedRows = ref<any[]>([]);

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const formData = reactive({
  id: "",
  userAccount: "",
  userPassword: "",
  userName: "",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  isDelete: 0,
});

// 页面加载时获取用户列表
onMounted(async () => {
  await fetchUserList();
});

// 获取用户列表
const fetchUserList = async () => {
  try {
    const userQuery: UserQueryRequest = {
      current: pagination.currentPage,
      pageSize: pagination.pageSize,
      userName: searchForm.userName,
      userRole: searchForm.userRole,
    };
    const response = await UserControllerService.listUserByPageUsingPost(
      userQuery
    );
    console.log("接口响应数据:", response); // 调试信息
    tableData.value = response.data.records || [];
    pagination.total = response.data.total || 0; // 确保 total 字段正确绑定
    console.log("分页数据:", tableData.value.length);
  } catch (error) {
    ElMessage.error("获取用户列表失败");
    console.error("接口调用错误:", error);
  }
};

// 搜索
const handleSearch = async () => {
  pagination.currentPage = 1;
  await fetchUserList();
  ElMessage.success("搜索成功");
};

// 重置搜索
const resetSearch = async () => {
  Object.assign(searchForm, {
    userAccount: "",
    userName: "",
    userRole: "",
  });
  pagination.currentPage = 1;
  await fetchUserList();
};

// 新增用户
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  Object.assign(formData, {
    userAccount: "",
    userPassword: "",
    userName: "",
    userAvatar: "",
    userProfile: "",
    userRole: "",
    isDelete: 0,
  });
};

// 编辑用户
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.assign(formData, row);
};

// 禁用用户（这里假设是删除用户操作）
const handleDisable = async (row: any) => {
  const deleteRequest: DeleteRequest = {
    id: row.id, // 假设后端接口以id作为删除依据，需要根据实际情况调整
  };
  await ElMessageBox.confirm("确定要删除该用户吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const response = await UserControllerService.deleteUserUsingPost(
        deleteRequest
      );
      if (response.data) {
        ElMessage.success("删除成功");
        await fetchUserList();
      }
    } catch (error) {
      ElMessage.error("删除用户失败");
    }
  });
};
const router = useRouter();
const store = useStore();
// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid) => {
    if (valid) {
      const requestData: UserUpdateRequest = {
        id: formData.id,
        userName: formData.userName,
        userAvatar: formData.userAvatar,
        userProfile: formData.userProfile,
        userRole: formData.userRole,
      };
      if (dialogType.value === "add") {
        UserControllerService.addUserUsingPost(requestData as UserAddRequest)
          .then((response) => {
            if (response.data) {
              ElMessage.success("添加成功");
              dialogVisible.value = false;
              fetchUserList();
            } else {
              ElMessage.error("添加用户失败");
            }
          })
          .catch((error) => {
            ElMessage.error("添加用户失败");
          });
      } else {
        UserControllerService.updateUserUsingPost(
          requestData as UserUpdateRequest
        )
          .then((response) => {
            if (response.data) {
              ElMessage.success("修改成功");
              dialogVisible.value = false;
              fetchUserList();
            } else {
              ElMessage.error("修改用户失败");
            }
          })
          .catch((error) => {
            ElMessage.error("修改用户失败");
          });
      }
    }
  });
};

// 排序变化
const handleSortChange = (column: any) => {
  console.log("排序字段:", column.prop);
  console.log("排序方式:", column.order);
  // 这里可以根据排序字段和方式调用 API 重新获取数据
  // 目前只是打印信息，未实现实际功能
};

// 每页条数变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchUserList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchUserList();
};
const currentPage = ref();
</script>

<style scoped>
.avatar-uploader {
  @apply border border-gray-300 border-dashed rounded-lg cursor-pointer hover:border-primary-500 transition-colors;
}
.avatar-uploader-icon {
  @apply flex items-center justify-center w-24 h-24 text-gray-400 text-2xl;
}
:deep(.el-upload) {
  @apply block;
}
.el-pagination {
  display: block !important;
  padding: 12px 5px !important; /* 确保内边距 */
  overflow: visible !important; /* 防止隐藏 */
}
.el-pagination__total is-first {
  display: none;
}
</style>
